import axios from 'axios'
import { baseURL, timeout } from './config'
import { useUserStore } from '@/stores'
import { ElMessage } from 'element-plus'
import router from '@/router'
export const sevice = axios.create({
  baseURL,
  timeout,
})

// 添加请求拦截器
axios.interceptors.request.use(
  function (config) {
    // 在发送请求之前做些什么
    const useStore = useUserStore()
    const token = useStore.token
    if (token) {
      config.headers.Authorization = token
    }
    return config
  },
  function (error) {
    // 对请求错误做些什么
    return Promise.reject(error)
  },
)

// 添加响应拦截器
axios.interceptors.response.use(
  function (response) {
    if (response.data.code === 0) {
      return response
    }
    ElMessage.error(response.data.message || '服务异常')

    return Promise.reject(response.data)
  },
  function (error) {
    if (error.response?.status === 401) {
      router.push('/login')
    }
    ElMessage.error(error.response.data.message || '服务异常')
    return Promise.reject(error)
  },
)
